package com.jiyongjun.bms.base.configurer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;

/**
 * description:
 *
 * @author yongjun.ji
 * @date 2019/3/1 15:02
 */
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    // @Autowired
    // private CustomSysUserService customSysUserService;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                // 对/、/login 不拦截
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
                .antMatchers("/", "/login", "/getCode").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/")
                .failureUrl("/login?error")
                .permitAll()
                .and()
                .rememberMe()
                // 指定cookie有效期
                .tokenValiditySeconds(2*7*24*60*60)
                // 指定cookie中的私钥
                // .key("myKey")
                .and()
                .logout().permitAll()
                .and()
                // 暂时关闭csrf，否则put请求403
                .csrf().disable()
                // 跨域请求配置
                .headers().frameOptions().sameOrigin();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("admin").password("{noop}123456").roles("ADMIN")
                .and()
                .withUser("user").password("{noop}123456").roles("USER")
                .and()
                .withUser("root").password("{noop}root").roles("ADMIN");
        // auth.userDetailsService(customSysUserService)
                //TODO 新增用户密码加密
                // .passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 不拦截静态资源
        web.ignoring().antMatchers("/js/**", "/assets/**", "/**/favicon.ico", "/plugin/**");
    }
}
